<?php

namespace oa\services;

use oa\services\UserService;
use Yii;
use common\components\Yarray;
use oa\models\Menu;
use oa\models\User;
use common\models\PrivRole as PrivRoleModel;
use common\models\PrivAction as PrivActionModel;

class MenuService extends BaseService
{

    public static function save($id = 0)
    {
        if (empty($id)) {
            $model = new Menu();
            $model->scenario = Menu::SCENARIO_ADD;
        } else {
            $model = self::one($id);
            $model->scenario = Menu::SCENARIO_ADD;
        }
        $data = [
            'pid'     => Yii::$app->request->post('pid'),
            'name'    => Yii::$app->request->post('name'),
            'url'     => Yii::$app->request->post('url'),
            'actions' => Yii::$app->request->post('actions'),
            'sort'    => Yii::$app->request->post('sort'),
            'icon'    => Yii::$app->request->post('icon'),
            'is_show' => Yii::$app->request->post('is_show', 0),
            'is_test' => Yii::$app->request->post('is_test', 0),
            'is_target' => Yii::$app->request->post('is_target', 0),
            'status' => Yii::$app->request->post('status', 1),
            'remark'  => Yii::$app->request->post('remark'),
        ];
        return $model->_save($data, 1);
    }

    public static function getFullVisit($menu_id)
    {
        $row = Menu::find()
            ->select('id,pid,name')
            ->where(['id' => $menu_id, 'status' => 1])
            ->asArray()
            ->one();
        $list = [];
        if (!empty($row)) {
            $list = [$row];
            if (!empty($row['pid'])) {
                self::getParents($row['pid'], $list);
            }
        }
        return $list;
    }

    /**
     * 查询菜单上级
     * @return [type] [description]
     */
    public static function getParents($pid, &$result = [])
    {
        $row = AuthMenu::find()
            ->select('id,pid,name')
            ->where(['id' => $pid, 'status' => 1])
            ->asArray()
            ->one();
        if (!empty($row)) {
            array_unshift($result, $row);
            if (!empty($row['pid'])) {
                self::getParents($row['pid'], $result);
            }
        }
    }

    public static function getAll()
    {
        return Yarray::list_to_tree(Menu::find()->select('pid,id,name')->where('status=1')->orderBy('sort desc,id asc')->asArray()->all());
    }

	public static function getList()
    {
        $query = Menu::find();
        $query->where('status<>-1');
        $query->filterWhere(['pid' => Yii::$app->request->get('pid')]);
        $query->andFilterWhere(['id' => Yii::$app->request->get('id')]);
        $query->andFilterWhere(['status' => Yii::$app->request->get('status')]);
        $query->andFilterWhere(['like', 'name', Yii::$app->request->get('name')]);
        $countQuery = clone $query;
        $query->orderBy('sort desc,id asc');
        $query->offset(Yii::$app->request->get('offset'));
        $query->limit(Yii::$app->request->get('limit'));
        $rows = $query->asArray()->all();
        foreach ($rows as $k => $v) {
            $rows[$k]['updated_at'] = date('Y-m-d H:i', $v['updated_at']);
        }
        return ['rows' => $rows, 'total' => $countQuery->count()];
    }

	/**
	 * 查询用户的菜单
	 * @return [type] [description]
	 */
	public static function getAllByUid($uid = 0)
	{
        $query = Menu::find()
            ->select(['id', 'pid', 'name', 'url', 'icon', 'actions'])
            ->where(['status' => 1]);
         if (!UserService::isSuper()) {
             if ($uid == 0) {
                 $role_id = Yii::$app->user->identity->role_id;
             } else {
                 $role_id = User::find()->select('role_id')->where(['id' => $uid])->asArray()->scalar();
             }
             $role_menu_ids = RoleModel::find()->select('menu_ids')->where(['id' => $role_id])->scalar();
             if (empty($role_menu_ids)) {
                 return [];
             }
             $query->andWhere(['id' => explode(",", $role_menu_ids)]);
         }
		return $query->orderBy('sort asc,id desc')->asArray()->all();
	}

    /**
     * 查询当前访问的菜单
     * @return [type] [description]
     */
	public static function getCurrVisit()
    {
        $controller = Yii::$app->controller->id;
        $action = Yii::$app->controller->action->id;
        $module = Yii::$app->controller->module->id;
        $href = '/';
        if ($module == Yii::$app->id) {
            $module = '';
        } else {
            $href .= $module . '/';
        }
        $href .= $controller . '/' . $action;
        $res = AuthMenu::find()
            ->select('id,pid_path,name')
            ->where(['href' => $href, 'is_del' => 0, 'status' => [1, 3]])
            ->asArray()
            ->one();
        if (!$res) {
            return false;
        }
        return $res;
    }

    public static function one($map, $toArray = 0)
    {
        $query = Menu::find()->where('status<>-1');
        if (is_string($map) && preg_match('/^[1-9]+[\d]*$/', $map)) {
            $query->andWhere('id=:id', [':id' => $map]);
        } elseif (is_array($map)) {
            $query->andWhere($map[0], $map[1]);
        } else {
            $query->andWhere($map);
        }
        if ($toArray == 1) {
            $query->asArray();
        }
        return $query->one();
    }

    public static function set($force = 1)
    {
        if ($force == 1 || !Yii::$app->session->has('menus')) {
            $menus = Yarray::list_to_tree(self::getAllByUid());
            Yii::$app->session->set('menus', $menus);
            if (Yii::$app->session->has('menus')) {
                return $menus;
            }
            return false;
        }
        return Yii::$app->session->get('menus');
    }

    public static function render($visit_menu_id = 0, $menus = [], $depth = 0)
    {
        if (empty($menus)) {
            $menus = Yarray::list_to_tree(Yii::$app->session->get('menus'));
        }
        $html = '';
        if(!empty($menus)){
            foreach ($menus as $v) {
                $exists_submenu = empty($v['_child']) ? false : true;
                $html .= '<li class="'.($v['id'] == $visit_menu_id ? 'active' : '').'">';
                if (!$exists_submenu) {
                    $html .= '<a href="/'.$v['url'].'">';
                    if (!empty($v['icon'])) {
                        $html .= '<i class="menu-icon '.$v['icon'].'"></i>';
                    } elseif ($depth > 1) {
                        $html .= '<i class="menu-icon fa fa-caret-right"></i>';
                    }
                    $html .= '<span class="menu-text">'.$v['name'].'</span>';
                    $html .= '</a>';
                }else{
                    $html .= '<a href="javascript:" class="dropdown-toggle">';
                    $html .= '<i class="menu-icon '.(!empty($v['icon']) ? $v['icon'] : 'fa fa-caret-right').'"></i>';
                    $html .= '<span class="menu-text">'.$v['name'].'</span>';
                    $html .= '<b class="arrow fa fa-angle-down"></b>';
                    $html .= '</a>';
                    $html .= '<b class="arrow"></b>';
                    $html .= '<ul class="submenu">';
                    $html .= self::render($visit_menu_id, $v['_child'], $depth++);
                    $html .= '</ul>';
                }
                $html .= '</li>';
            }
        }
        return $html;
    }

    public static function remove($id)
    {
        if (Yii::$app->request->isAjax) {
            $model = self::one(['id=:id AND status<>-1', [':id' => $id]]);
            $model->scenario = Menu::SCENARIO_REMOVE;
            return $model->_save();
        }
    }

    public static function disable($id)
    {
        if (Yii::$app->request->isAjax) {
            $model = self::one(['id=:id AND status=1', [':id' => $id]]);
            $model->scenario = Menu::SCENARIO_DISABLE;
            return $model->_save();
        }
    }

    public static function enable($id)
    {
        if (Yii::$app->request->isAjax) {
            $model = self::one(['id=:id', [':id' => $id]]);
            $model->scenario = Menu::SCENARIO_ENABLE;
            $model->status = 1;
            return $model->save();
            echo $model->id;
            exit;
            $model->status = 1;
            return $model->_save();
        }
    }

}